import 'dart:io';
import 'dart:typed_data';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
//    debugPaintSizeEnabled = true; //打开布局边界
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Image示例demo'),
        ),
        body: Center(
          child: Column(
            children: <Widget>[
              Image.network(
                  //1.从网络中加载
                  'https://pic2.zhimg.com/v2-84e0420e5cc2660f43f9d0e3e50db42c_is.jpg',
                  width: 100.0,
                  height: 100.0),
              Image.asset('assets/images/1.jpg'), //2.从assets中加载
              MemoryImageWidget(), //3.从内存中加载
              //4.从文件加载
              FileImageWidget(),
            ],
          ),
        ),
      ),
    );
  }
}

class FileImageWidget extends StatefulWidget {
  @override
  _FileImageWidgetState createState() => _FileImageWidgetState();
}

class _FileImageWidgetState extends State<FileImageWidget> {
  File _image;

  Future getImage() async {
    //异步加载图片
    ImagePicker imagePicker = ImagePicker();
    var file = await ImagePicker.pickImage(source: ImageSource.gallery);
    print('file:' + file.toString());
    setState(() {
      //通知视图刷新
      _image = file;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Center(
          child: _image == null
              ? Text('未选择图片')
              : Image.file(
                  _image,
                  width: 200.0,
                  height: 200.0,
                ),
        ),
        FlatButton(
          onPressed: getImage,
          child: Text(
            '选择图片',
            style: TextStyle(color: Color(0xff0000ff)),
          ),
        )
      ],
    );
  }
}

//Flutter中每一个像素都可以由开发者掌控
class MemoryImageWidget extends StatefulWidget {
  @override
  _MemoryImageWidgetState createState() => _MemoryImageWidgetState();
}

class _MemoryImageWidgetState extends State<MemoryImageWidget> {
  Uint8List bytes; //??啥鬼东西
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    rootBundle.load('assets/images/1.jpg').then((data) {
      if (mounted) {
        setState(() {
          bytes = data.buffer.asUint8List();
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    final _decoration = BoxDecoration(
      image: bytes == null ? null : DecorationImage(image: MemoryImage(bytes)),
    );
    return Container(
      width: 200.0,
      height: 200.0,
      decoration: _decoration,
    );
  }
}
